<!--
 * @Author: jingjingzheng 1742420988@qq.com
 * @Date: 2023-12-05 14:18:07
 * @LastEditors: jingjingzheng 1742420988@qq.com
 * @LastEditTime: 2024-01-15 22:24:56
 * @FilePath: \mdbj-ui\src\views\datamanager\road\dataPanel.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container" style="overflow:scroll">
    <!-- title -->
    <el-row>
      <el-col  :span="24" class="title-row">
        <span :style="{ color: theme }">| 道路信息管理</span>
      </el-col>
    </el-row>
    <!-- 表单 -->
    <div v-show="true">
      <!-- 查询按钮 新增 删除-->
      <div style="display: flex; justify-content: space-between">
        <el-switch v-model="showSearch" style="height: 33px" active-text="查询条件" active-color="#13ce66"
          @change="switchChange">
        </el-switch>
        <!-- 新增删除-->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['datamanager:road:add']">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['datamanager:road:remove']">删除</el-button>
          </el-col> -->
          <!-- <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-download" size="mini" :disabled="multiple"
              @click="handleExport()" v-hasPermi="['datamanager:road:export']">导出</el-button>
          </el-col> -->
        </el-row>
      </div>

      <!-- 查询条件-->
      <el-form ref="form" :model="queryParams" label-width="80px" size="small" :inline="true" v-show="showSearch"
        class="queryPanel">
        <!-- 按保洁单位查询 -->
        <el-form-item label="道路名称">
          <el-input v-model="queryParams.name" style="width: 10vw"></el-input>
        </el-form-item>
        <el-form-item label="道路等级">
          <el-select v-model="queryParams.roadclass_js" placeholder="请选择道路等级" style="width: 10vw" clearable>
            <el-option v-for="dict in dict.type.sys_roadclass_js" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="保洁单位">
          <el-select v-model="queryParams.cleancompany" placeholder="请选择保洁单位" style="width: 10vw" clearable>
            <el-option v-for="dict in dict.type.sys_cleancompany" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.data_status" placeholder="请选择道路状态" style="width: 10vw" clearable>
            <el-option v-for="dict in dict.type.road_data_status" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>

        <!-- 按空间范围查询 -->
        <el-form-item label="空间范围" size="normal">
          <el-button type="info" size="mini" @click="drawExtent('rectangle')">矩形</el-button>
          <el-button type="info" size="mini" @click="drawExtent('polygon')">多边形</el-button>
        </el-form-item>
      </el-form>
      <!-- 查询/重置按钮   -->
      <el-row :gutter="20" style="text-align: center" v-show="showSearch">
        <el-button v-hasPermi="['datamanager:road:query']" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-row>

      <!-- 显示查询结果表单 -->
      <el-table :data="features" v-loading="loading" stripes highlight-current-row :height="tableHeight"
        @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="序号" type="index" width="50"> </el-table-column>
        <!-- <el-table-column label="objectid" align="center" prop="attributes.objectid" width="100" /> -->
        <el-table-column label="道路名称" width="150" align="center" :show-overflow-tooltip="true"
          prop="attributes.name"></el-table-column>
          <el-table-column label="保洁公司" width="150" align="center" :show-overflow-tooltip="true"
          prop="attributes.cleancompany"></el-table-column>
        <el-table-column label="道路等级" width="100" align="center" :show-overflow-tooltip="true"
          prop="attributes.roadclass_js">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_roadclass_js" :value="scope.row.attributes.roadclass_js" />
          </template>
        </el-table-column>
        <el-table-column label="道路长度(m)" width="100" align="center" :show-overflow-tooltip="true"
          prop="attributes.length">
          <template slot-scope="scope">
            <div v-if="scope.row.attributes.length">
              {{scope.row.attributes.length.toFixed(2)}}
            </div>
            <div v-if="!scope.row.attributes.length">
              {{scope.row.attributes.length}}
            </div>
          </template>
        </el-table-column>
          <el-table-column label="状态" width="100" align="center" :show-overflow-tooltip="true"
          prop="attributes.data_status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.road_data_status" :value="scope.row.attributes.data_status" />
          </template>
        </el-table-column>

            <!-- 操作模块 -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view"
              @click="handleView(scope.row, scope.index)">详情</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['datamanager:road:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-location-outline"
              @click="handleLocate(scope.row, scope.index)">定位</el-button>
            <!-- <el-button v-if="scope.row.attributes.data_status =='1'" size="mini" type="text" icon="el-icon-plus"
              @click="handleAddroadsurface(scope.row, scope.index)">新增道路面</el-button> -->
            <!-- 判断数据状态显示删除按钮 -->
            <el-button v-if="scope.row.attributes.data_status =='1'" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['datamanager:road:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        layout="total, sizes,prev, pager, next" @pagination="getList" />
    </div>
  </div>
</template>

<script>
import FeatureLayer from "@arcgis/core/layers/FeatureLayer";
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer";
import SketchViewModel from "@arcgis/core/widgets/Sketch/SketchViewModel";

export default {
  inject: ["toggleComponent"],
  components: {
    FeatureLayer,
    SketchViewModel,
  },
  props: {
    //将mapview定义为一个空对象
    mapview: { default: () => { } },
  },
  dicts: [
    "sys_roadclass_js",
    "sys_cleancompany",
    "road_data_status",
  ],
  computed: {
    theme() {
      return this.$store.state.settings.theme;
    },
  },
  data() {
    return {
      // 表格高度
      tableHeight: "75vh",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        name: undefined,
        roadclass_js: undefined,
        cleancompany: undefined,
        data_status: undefined,
        length: undefined,
        geometry: null,
      },
      // 显示搜索条件
      showSearch: false,
      // 当前页要素集合
      features: [],
      // 总条数
      total: 0,
      // 要素图层
      featureLayer: undefined,
      // 要素图层url
      featureLayerUrl: window.mapConfig.operationLayers.featurelayers["roadlayer"].url,
      // 遮罩层
      loading: false,
      // 属性查询条件
      whereClause: undefined,
      // 空间查询范围
      queryExtent: undefined,
      // 图层视图
      layerView: undefined,
      // 高亮图形
      highlight: undefined,
      // 选中的要素
      selectFeatures: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 选中要素数量
      selectnum: 0,
      // 监听点击view事件
      clickviewevent: undefined,
    }
  },
  // activated​ 若组件实例是 <KeepAlive> 缓存树的一部分，当组件被插入到 DOM 中时调用。
  activated() {
    if(this.featureLayer == undefined){
      this.initFeatureLayer();
    }else{
      this.highlight?.remove();
    }
    this.getList();
  },
  methods: {
    initFeatureLayer() {
      let _self = this;
      _self.highlight?.remove();
      _self.featureLayer = new FeatureLayer({
        title: "道路单线",
        url: this.featureLayerUrl,
        outFields: ["objectid"],
      })
      _self.mapview.map.addMany([_self.featureLayer])
      // 获取当前图层视图
      _self.mapview.whenLayerView(_self.featureLayer).then((layerView) => {
        console.log(layerView);
        _self.layerView = layerView;
      })
    },
    /**
    * @description: 根据查询参数构建where查询条件
    * @return {*}
    */
    getWhereClause() {
      let _self = this;
      //   queryParams
      let whereClause = "1=1";
      if (_self.queryParams.name)
        whereClause +=
          " and name like '%" + _self.queryParams.name + "%'";
      if (_self.queryParams.roadclass_js)
        whereClause +=
          " and roadclass_js = '" + _self.queryParams.roadclass_js + "'";
      if (_self.queryParams.cleancompany)
        whereClause +=
          " and cleancompany = '" + _self.queryParams.cleancompany + "'";
      if (_self.queryParams.data_status)
        whereClause +=
          " and data_status = '" + _self.queryParams.data_status + "'";
      return whereClause;
    },
    getList() {
      let _self = this;
      _self.loading = true;
      _self.whereClause = _self.getWhereClause();
      // 先构建用于查询数据总条数的查询参数对象
      let queryParams = {
        // 空间查询方式，相交查询
        spatialRelationship: "intersects",
        // 空间查询范围
        geometry: _self.queryExtent == null ? null : _self.queryExtent.geometry, // 草绘要素几何
        // 输出字段
        outFields: ["objectid"],
        where: _self.whereClause,
      };
      // 首先查询数据总条数用于渲染分页组件值
      _self.featureLayer.queryFeatureCount(queryParams).then((numResults) => {
        _self.total = numResults;
      });
      // 分页查询并在表格展示数据
      queryParams = {
        spatialRelationship: "intersects",
        geometry: _self.queryExtent == null ? null : _self.queryExtent.geometry, // 草绘要素几何
        start: (_self.queryParams.pageNum - 1) * _self.queryParams.pageSize,
        num: _self.queryParams.pageSize,
        outFields: ["objectid","code", "name", "roadclass_js", "cleancompany", "Shape__Length","length","data_status"],
        returnGeometry: true,
        orderByFields: ["objectid"],
        where: _self.whereClause,
      };
      // 查询数据
      _self.featureLayer.queryFeatures(queryParams).then((featureSet) => {
        _self.features = featureSet.features;
      });
      _self.loading = false
      // Get the screen point from the view's click event
      _self.mapview.on("click", function (event) {
        // Search for graphics at the clicked location. View events can be used
        // as screen locations as they expose an x,y coordinate that conforms
        // to the ScreenPoint definition.
        _self.mapview.hitTest(event).then(async function (response) {
          if (response.results.length) {
            let graphic = response.results.filter(function (result) {
              // check if the graphic belongs to the layer of interest
              return result.graphic.layer === _self.featureLayer;
            })[0].graphic;
            _self.handleLocate(graphic, true);
            let queryParams = {
              outFields: ["*"],
              where: `objectid=${graphic.attributes["objectid"]}`,
              returnGeometry: true,
            };
            const featureSet = await _self.featureLayer.queryFeatures(
              queryParams
            );
            const feature = featureSet.features[0];

            let paramObj = {
              feature: feature,
              featureLayer: _self.featureLayer,
              selectedGraphic: _self.selectedGraphic,
            };
            if(_self.clickviewevent !== undefined){
              // this.detailPanel.cancel();
              // _self.$message.error("请关闭详情信息");
            };
            _self.clickviewevent= true;
            _self.toggleComponent("detailPanel", paramObj);

          }
        });
      });
    },
    /**
   * @description: 切换查询面板显示隐藏
   * @param {*} val
   * @return {*}
   */
    switchChange(val) {
      console.log(val);
      if (val) {
        this.tableHeight = "60vh";
      } else this.tableHeight = "75vh";
    },
    /**
     * @description: 查询按钮
     * @return {*}
     */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /**
     * @description: 重置查询条件
     * @return {*}
     */
    resetQuery() {
      console.log('resetQuery');
      let _self = this;
      _self.queryParams.pageNum = 1;
      _self.queryParams.pageSize = 20;
      _self.queryParams.name = undefined;
      _self.queryParams.roadclass_js = undefined;
      _self.queryParams.cleancompany = undefined;
      _self.queryParams.data_status = undefined;
      _self.queryParams.name = undefined;
      _self.whereClause = undefined;
      _self.queryExtent = undefined;
      _self.getList();
      _self.clearGraphics();
    },
    /**
     * @description: 绘制查询范围
     * @param {*} drawType 图形类型，rectangle or polygon
     * @return {*}
     */
    drawExtent(drawType) {
      let _self = this;
      _self.clearGraphics();
      // 清除上一个临时草图
      // 添加草绘微件
      // 初始化一个临时图层
      const graphicsLayerSketch = new GraphicsLayer();
      const sketchViewModel = new SketchViewModel({
        id: drawType,
        view: _self.mapview,
        layer: graphicsLayerSketch,
        polygonSymbol: window.mapConfig.symbols.selectExtent,
      });
      sketchViewModel.on("create", (event) => {
        if (event.state === "complete") {
          console.log("Sketch complete");
          // 地图上添加绘制范围
          _self.mapview.graphics.add(event.graphic);
          _self.queryExtent = event.graphic;
        }
      });
      sketchViewModel.create(drawType);
    },
    /**
    * @description: 清除临时图形
    * @return {*}
    */
    clearGraphics() {
      let _self = this;
      // 清除临时图形
      _self.mapview.graphics.removeAll()
    },
    /**
     * @description: 详细按钮操作
     * @param {*} row 按钮所在数据行
     * @return {*}
     */
    async handleView(row) {
      console.log(row);
      let _self = this;
      let queryParams = {
        outFields: ["*"],
        where: `objectid=${row.attributes["objectid"]}`,
        returnGeometry: true,
      };
      const featureSet = await _self.featureLayer.queryFeatures(queryParams);
      const feature = featureSet.features[0];
      // const featureLayer = new FeatureLayer({
      //   title: "道路中心线",
      //   url: this.featureLayerUrl,
      //   outFields: ["objectid"],
      //   definitionExpression: `objectid=${row.attributes["objectid"]}`,
      // });
      _self.handleLocate(row)
      let paramObj = {
        feature: feature,
        featureLayer: _self.featureLayer,
        highlight: _self.highlight
      };
      _self.toggleComponent("detailPanel", paramObj)
    },
    /**
     * @description: 修改按钮
     * @return {*}
     */
    async handleUpdate(row) {
      let _self = this;
      let queryParams = {
        outFields: ["*"],
        where: `objectid=${row.attributes["objectid"]}`,
        returnGeometry: true,
      };
      const featureSet = await _self.featureLayer.queryFeatures(queryParams);
      const feature = featureSet.features[0];
      // const featureLayer = new FeatureLayer({
      //   title: "道路中心线",
      //   url: this.featureLayerUrl,
      //   outFields: ["objectid"],
      //   definitionExpression: `objectid=${row.attributes["objectid"]}`,
      // });
      _self.handleLocate(row)
      let paramObj = {
        feature: feature,
        featureLayer: _self.featureLayer,
        highlight: _self.highlight
      };
      _self.toggleComponent("editPanel", paramObj);
    },
    /**
     * @description: 删除按钮
     * @return {*}
     */
    handleDelete(row) {
      let _self = this;
      _self.selectnum = _self.selectFeatures.length
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const deleteFeatures =
            row == null && _self.selectFeatures.length != 0
              ? _self.selectFeatures
              : [row];
          const edits = {
            deleteFeatures: deleteFeatures,
          };
          // 删除要素
          _self.featureLayer.applyEdits(edits).then((editsResult) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            console.log(editsResult);
            _self.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    /**
     * @description: 定位按钮操作
     * @param {*} row
     * @return {*}
     */
    async handleLocate(row) {
      let _self = this;
      let feature = undefined;
      feature = row;
      // 移除前一个高亮图形
      _self.highlight?.remove();
      // 高亮显示当前页要素;
      _self.highlight = _self.layerView.highlight(feature);
      if (feature.geometry == null) {
        _self.$message.error("暂无空间信息");
        return;
      }
      _self.mapview
        .goTo({
          target: feature.geometry,
          // zoom: _self.zoomLevel,
        })
        .catch((error) => {
            console.error(error);
        });
    },
    /**
     * @description: 新增数据
     * @return {*}
     */
    // 多选框选中数据
    handleSelectionChange(selection) {
      // this.ids = selection.map((item) => item.attributes.objectid);
      this.selectFeatures = selection;
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      let _self = this;
      let paramObj = {
        featureLayer: _self.featureLayer,
      };
      _self.toggleComponent("addPanel", paramObj);
    },
    handleAddroadsurface(row) {
      let _self = this;
      let feature = row;
      const paramObj = {
        feature: feature,
      };
      _self.handleLocate(row)
      this.toggleComponent("roadsurfaceAddPanel", paramObj);
    },

  }
};
</script>

<style lang="scss" scoped>
.title-row {
  width: 100%;
  font-size: 18px;
  font-weight: bold;
  /* color: #409eff; */
  /* margin-bottom: 1vh; */
}
</style>
